import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/toast.dart';
import 'package:flutter_enjoy_plus/utils/tokenManager.dart';

import '../../utils/Emitter.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 手机号控制器
  final TextEditingController _phoneController = TextEditingController();
  // 验证码控制器
  final TextEditingController _codeController = TextEditingController();

  _sendCode() async {
    // 判断手机号是否合法 不为空 + 正则
    // 拿着手机号 发送请求 -> 获取验证码
    // 填充验证码 (手动找network 填充)
    // 开启倒计时
    if (_count == 60){
      if (_phoneController.text.isEmpty) {
        return PromptAction.showErrorToast('请输入手机号');
      }
      //r  rawfile 原始字符 代表了 \d 不是普通字符 是一个元字符 (具有特殊含义)
      RegExp reg = RegExp(r'^1[3-9]\d{9}$');
      if (!reg.hasMatch(_phoneController.text)) {
        return PromptAction.showErrorToast('请输入正确的手机号');
      }
      setState(() {
        _count--;
      });
      final res = await getCodeApi({'mobile': _phoneController.text});
      Future.delayed(const Duration(seconds: 2),(){
        _codeController.text = res['code'];
      });
      beginCount();
    }
  }
  // 登录
  login() async{
    if (_phoneController.text.isEmpty){
      return PromptAction.showErrorToast('手机号不能为空');
    }
    if (_codeController.text.isEmpty){
      return PromptAction.showErrorToast('验证码不能为空');
    }
    RegExp phoneReg = RegExp(r'^1[3-9]\d{9}$');
    if (!phoneReg.hasMatch(_phoneController.text)) {
      return PromptAction.showErrorToast('手机号格式不正确');
    }
    RegExp codeReg = RegExp(r'^\d{6}$');
    if (!codeReg.hasMatch(_codeController.text)) {
      return PromptAction.showErrorToast('验证码格式不正确');
    }
  final res = await loginApi({'mobile': _phoneController.text, 'code': _codeController.text});
    _timer?.cancel();
    // 返回上一页
    Navigator.pop(context);
    // 存token
    tokenManager.setToken(res['token'],refreshToken:  res['refreshToken']);
    // 一旦登录成功，通知我的页面，重新获取用户信息，进行渲染
    eventBus.fire(LoginEvent());
  }



  int _count = 60;
  Timer? _timer;
  beginCount(){
    if (_count == 60){
      _timer = Timer.periodic(const Duration(seconds: 1), (timer){
        if (_count < 1){
          setState(() {
            _count = 60;
          });
          // 停止定时器
          _timer?.cancel();
        } else {
          setState(() {
            _count--;
          });
        }
      });
    } else {
      PromptAction.showToast('请稍后再试');
    }
  }
  // 页面或者组件被销毁时，清除定时器
  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
  Widget getTimeShow() {
    if (_count < 60 &&  _count > 0){
      return Text('$_count秒后重试');
    } else {
      return const Text('获取验证码');
    }
    
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      _phoneController.text = '13712341234';
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('登录'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Container(
        padding: const EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const Row(
              children: [
                Text(
                  '登录',
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '加入享+, 让生活更轻松',
                  style: TextStyle(fontSize: 15),
                )
              ],
            ),
            const SizedBox(height: 30),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  child: TextField(
                    controller: _phoneController,
                    decoration: const InputDecoration(
                      labelText: '手机号',
                      hintText: '请输入手机号',
                    ),
                  ),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    shadowColor: Colors.transparent,
                    foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    //
                    _sendCode();
                  },
                  child:getTimeShow(),
                ),
              ],
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _codeController,
              decoration: const InputDecoration(
                labelText: '验证码',
                hintText: '请输入6位验证码',
              ),
            ),
            const SizedBox(height: 8),
            const Row(
              children: [
                Text(
                  '未注册手机号经验证后将自动登录',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 50),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      login();
                    },
                    child: const Text(
                      '登录',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
